package memorphic.samplr.views.itemRenderers
{
	import flash.events.MouseEvent;
	
	import memorphic.samplr.models.SamplrPhoto;
	
	import mx.containers.Canvas;
	import mx.controls.CheckBox;
	import mx.controls.Image;
	import mx.controls.Label;

	public class TestTileRenderer extends Canvas
	{
		private var image:Image;
		
		private var photo:SamplrPhoto;
		
		private var checkBox:CheckBox;
		
		private var title:Label;
		
		private var photoOwner:Label;
		 
		public function TestTileRenderer()
		{
			super();
			width = 150;
			height = 150;
		}
		
		protected override function createChildren():void
		{
			super.createChildren();
			
			createImage();
			createCheckBox();
			
			photoOwner = new Label();
			photoOwner.truncateToFit = true;
			addChild(photoOwner);
			
			title = new Label();
			title.truncateToFit = true;
			addChild(title);
		}
		
		private function createImage():void
		{
			if (!image)
			{
				image = new Image();
				image.cacheAsBitmap = true;
				image.maintainAspectRatio = true;
				addChild(image);
			}
		}
		
		private function createCheckBox():void
		{
			if (!checkBox)
			{
				checkBox = new CheckBox();
				checkBox.addEventListener(MouseEvent.CLICK, onSelected);
				addChild(checkBox);
			}
		}
		
		protected override function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
		{
			super.updateDisplayList(unscaledWidth, unscaledHeight);
			
			setStyle("backgroundColor", "0xffffff");
			setStyle("backgroundAlpha", 0.7);
			
			image.x = (unscaledWidth - image.width)/2;
			image.y = (unscaledHeight - image.height)/2;
			
			photoOwner.width = 150;
			photoOwner.x = (unscaledWidth - photoOwner.width)/2;
			photoOwner.y = 5;
			
			title.width = 150;
			
			title.x = (unscaledWidth - title.width)/2;
			title.y = (unscaledHeight - title.height);
			
			checkBox.x = (unscaledWidth - checkBox.width)/2;
			checkBox.y = (unscaledHeight - checkBox.height);
		}
		
		protected override function commitProperties():void
		{
			super.commitProperties();
		}
		
		public override function set data(value:Object):void
		{
			super.data = value;
			
			if (photo != value)
			{
				photo = SamplrPhoto(value);
				createImage();
				image.source = photo.thumbnailURL;
				
				if (title) title.text = photo.title;
				if (photoOwner) photoOwner.text = photo.owner;
				
				createCheckBox();
				checkBox.selected = photo.selected;
			}
		}
		
		public override function get data():Object
		{
			return photo;
		}
		
		private function onSelected(evt:MouseEvent):void
		{
			photo.selected = checkBox.selected;
		}
	}
}